<template>
  <el-dialog v-model="dialogVisible" title="新增教师" center width="500" append-to-body>
    <el-form ref="formInstall" :model="form" status-icon :rules="rules" label-position="left" label-width="auto">
      <el-form-item label="姓名:" prop="name">
        <el-input v-model.trim="form.name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="性别:" prop="gender">
        <el-select v-model="form.gender" placeholder="请选择性别">
          <el-option label="男" :value="1" />
          <el-option label="女" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="年龄:" prop="age">
        <el-input v-model.trim="form.age" placeholder="请输入年龄" />
      </el-form-item>
      <el-form-item label="手机号码:" prop="phone">
        <el-input v-model.trim="form.phone" placeholder="请输入手机号码" />
      </el-form-item>
      <el-form-item label="邮箱:" prop="email">
        <el-input v-model.trim="form.email" placeholder="请输入邮箱" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="submit">确定</el-button>
        <el-button type="primary" @click="rest"> 重置 </el-button>
        <el-button type="primary" @click="cancel"> 取消 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { getDetailApi } from '@/api/teacher/index'

const dialogVisible = ref(false)

const open = async (id) => {
  if (id) {
    const res = await getDetailApi({ id })
    if (res.code == 200) {
      form.value = res.data
      ElMessage.success(res.msg)
    } else {
      ElMessage.error(res.msg)
    }
  }
  dialogVisible.value = true
}

const formInstall = ref(null)
const form = ref({
  name: '',
  gender: '',
  age: '',
  phone: '',
  email: '',
})
const rules = reactive({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  phone: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确格式的手机号', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '请输入正确格式的邮箱', trigger: 'blur' },
  ],
})

const submit = async () => {
  if (!formInstall.value) return
  formInstall.value.validate(async (valid) => {
    if (valid) {
      emit('submit', form.value)
      cancel()
    }
  })
}

const cancel = () => {
  dialogVisible.value = false
}

const rest = () => {
  formInstall.value.resetFields()
}

const emit = defineEmits(['submit'])
defineExpose({
  open,
})
</script>

<style scoped lang="scss"></style>
